﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Adp.Common;
using System;
using Yqd.Core;
using Yqd.Enm;
using Yqd.Controllers.Filter;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Yqd.Dto;
using System.Threading;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxSuperviseController : Controller
    {
        YqdContext ctx;
        DdService ddService;
        static string UnitCode = "";
        static string UnitName = "";

        public WxSuperviseController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        [User]
        public ActionResult GetList()
        {
            var l = WxUser.LogonInfo;
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            dynamic supervise = null;
            long TaskID = 0;
            int ItemID = 0, CooperativeID = 0;
            bool IsCurrentUnit = false;
            var ItemType = 事项类型.钉办督导;
            var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            if (SuperviseID > 0)
            {
                var r = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                if (r == null)
                {
                    return this.ToJson(new
                    {
                        success = true,
                        data = new List<object>()
                    });
                }
                TaskID = r.TaskID;
                ItemID = r.SuperviseID;

                if (r.UnitCode == l.UnitCode)
                {
                    IsCurrentUnit = true;
                }
                supervise = new
                {
                    r.TaskID,
                    r.SuperviseID,
                    CoordinateID = 0,
                    CooperativeID = 0,
                    ItemID = r.SuperviseID,
                    ItemType,
                    Principal = user.FirstOrDefault(m => m.EmployeeCode == r.EmployeeCode)?.Name,
                    r.Status,
                    r.Content,
                    r.Instime
                };
            }
            if (CoordinateID > 0)
            {
                var r = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == CoordinateID);
                if (r == null)
                {
                    return this.ToJson(new
                    {
                        success = true,
                        data = new List<object>()
                    });
                }
                if (r.UnitCode == l.UnitCode)
                {
                    IsCurrentUnit = true;
                }
                TaskID = r.TaskID;
                ItemID = r.CoordinateID;
                ItemType = 事项类型.协同管理;
                CooperativeID = r.CooperativeID;
                supervise = new
                {
                    r.TaskID,
                    SuperviseID = 0,
                    r.CoordinateID,
                    r.CooperativeID,
                    ItemID = r.CoordinateID,
                    ItemType,
                    r.Status,
                    Principal = user.FirstOrDefault(m => m.EmployeeCode == r.Coordinator)?.Name,
                    Content = r.Item,
                    r.Instime
                };
            }
            var scheme = ctx.Yqd_Scheme.Where(it => it.ItemID == ItemID && it.ItemType == ItemType).ToList();
            var DeptRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.部门管理员);
            var MsRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.市领导 || it == 角色类型.领导秘书);
            var plan = ctx.Yqd_JobPlan.Where(it => it.ItemID == ItemID && it.ItemType == ItemType).ToList();
            var progress = ctx.Yqd_PlanProgress.Where(it => it.ItemID == ItemID && it.ItemType == ItemType).ToList();
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            string CooperativeUnit = "", TaskName = "", LeaderUnitCode = "";
            if (task != null)
            {
                TaskName = task.TaskName;
                LeaderUnitCode = task.LeaderUnitCode;
            }
            var cooperative = ctx.Yqd_Cooperative.FirstOrDefault(it => it.CooperativeID == CooperativeID);
            if (cooperative != null) CooperativeUnit = cooperative.CooperativeUnit;
            var sm = scheme.Where(it => it.CheckStatus != 审核状态.退回);
            var pg = progress.Where(it => it.CheckStatus != 审核状态.退回);
            var a = ctx.Yqd_Assign.FirstOrDefault(it => it.ItemID == ItemID && it.ItemType == ItemType);
            object Assign = null;
            var IsLeadUnit = false;
            if (a != null)
            {
                IsLeadUnit = a.LeadUnit == l.UnitCode;
                Assign = new
                {
                    a.AssignID,
                    Unit = dept.FirstOrDefault(it => it.UnitCode == a.UnitCode)?.Name,
                    UnitCode = a.LeadUnit,
                    LeadUnit = dept.FirstOrDefault(it => it.UnitCode == a.LeadUnit)?.Name,
                    CooperativeUnit = string.IsNullOrWhiteSpace(a.CooperativeUnit) ? "" : string.Join(",", dept.Where(it => ("," + a.CooperativeUnit + ",").Contains("," + it.UnitCode + ",")).Select(it => it.Name)),
                    CompleteLimit = a.CompleteLimit.ToString("yyyy-MM-dd"),
                    ReportLimit = a.ReportLimit.ToString("yyyy-MM-dd"),
                    FeedbackLoop = a.FeedbackLoop == 进展反馈周期.自定义 ? a.Days + "天" : a.FeedbackLoop.ToString(),
                    ProgressInfo = a.ProgressInfo ?? "",
                    a.Days,
                    Material = !string.IsNullOrWhiteSpace(a.Material) ? JArray.Parse(a.Material) : new JArray(),
                    ReportTime = a.ReportTime?.ToString("yyyy-MM-dd") ?? "",
                    Instime = a.Instime.ToString("yyyy-MM-dd")
                };
            }
            var ap = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == ItemID && it.ItemType == ItemType).OrderByDescending(x => x.ApprovalID).FirstOrDefault();
            object SchemeApproval = null;
            if (ap != null)
            {
                SchemeApproval = new
                {
                    Leader = ap.Leader ?? "",
                    Dept = ap.Dept ?? "",
                    DeptLeader = ap.DeptLeader ?? "",
                    Attachment = !string.IsNullOrWhiteSpace(ap.Attachment) ? JsonConvert.DeserializeObject(ap.Attachment) : new object()
                };
            }
            return this.ToJson(new
            {
                success = true,
                IsCurrentUnit,
                DeptRole,
                MsRole,
                IsLeadUnit,
                TaskName,
                LeaderUnitCode,
                supervise.SuperviseID,
                supervise.CoordinateID,
                Content = supervise.Content ?? "",
                Instime = supervise.Instime.ToString("yyyy年M月d日"),
                Status = supervise.Status.ToString().Replace("推进", ""),
                supervise.Principal,
                CooperativeUnit,
                Tag = supervise.ItemType.ToString(),
                Assign,
                SchemeApproval,
                ShowSchemeHistory = scheme.Any(s => s.CheckStatus == 审核状态.退回),
                ShowScheme = DeptRole && Assign != null && (scheme.Count == 0 || scheme.Any(s => s.IsComplete)),
                Scheme = sm.OrderBy(it => it.Instime).Select(n => new
                {
                    n.SchemeID,
                    JobTarget = n.JobTarget?.Replace("\r\n", "<br/>"),
                    JobType = n.JobType.ToString(),
                    IsCheck = n.CheckStatus == Enm.审核状态.待审,
                    Plan = plan.Where(d => d.SchemeID == n.SchemeID).OrderBy(it => it.CompleteTime).Select(s => new
                    {
                        s.PlanID,
                        Measure = s.Measure ?? "",
                        CompleteTime = s.CompleteTime.ToString("yyyy-MM-dd"),
                        CooperativeUnit = string.IsNullOrWhiteSpace(s.CooperativeUnit) ? "" : string.Join(",", dept.Where(it => ("," + s.CooperativeUnit + ",").Contains("," + it.UnitCode + ",")).Select(it => it.Name)),
                        PlanStatus = s.PlanStatus.ToString(),
                        s.FlowIsOver,
                        ShowHistory = progress.Any(b => b.PlanID == s.PlanID && b.CheckStatus == 审核状态.退回),
                        LoopDate = string.IsNullOrWhiteSpace(s.TimeLine) || s.PlanStatus == 工作计划状态.已完成 ? new List<object>() : s.TimeLine.Split(",").Where(ld => !pg.Any(b => b.PlanID == s.PlanID && b.FeedbackTime == DateTime.Parse(ld) && (b.ProgressStatus == 0 || b.ProgressStatus == 任务状态.已完成))).Select(d => new { Name = d, Value = d }).ToList<object>(),
                        Progress = pg.Where(b => b.PlanID == s.PlanID).Select(p => new
                        {
                            p.ProgressID,
                            IsCheck = p.AuditStatus == 0,
                            ProgressInfo = p.ProgressInfo + (p.ProgressStatus != 任务状态.退回 ? " (" + p.ProgressStatus.ToString().Replace("推进", "") + ")" : ""),
                            ProgressStatus = p.ProgressStatus.ToString().Replace("推进", ""),
                            ProofMaterial = !string.IsNullOrWhiteSpace(p.ProofMaterial) ? JArray.Parse(p.ProofMaterial) : new JArray(),
                            p.Problem,
                            p.Experience,
                            p.CompleteCount,
                            p.CompletingCount,
                            fbTime = p.FeedbackTime.ToString("yyyy-MM-dd"),
                            ExperienceMaterial = !string.IsNullOrWhiteSpace(p.ExperienceMaterial) ? JArray.Parse(p.ExperienceMaterial) : new JArray(),
                            Feedbacker = user.FirstOrDefault(u => u.EmployeeCode == p.EmployeeCode)?.Name,
                            FeedbackInstime = p.Instime.ToString("yyyy-MM-dd HH:mm:ss")
                        })
                    })
                })
            });
        }

        /// <summary>
        /// 10：工作方案审核；20：进展反馈审核；30：办结报告审核
        /// </summary>
        /// <returns></returns>
        [User]
        public ActionResult GetSuperviseList()
        {
            var TaskID = Form.GetLong("TaskID");
            var Status = Form.GetInt("Status", 0);
            var year = Form.GetInt("Year", 0);
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 0);
            var data = new List<dynamic>();
            var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            var r = ctx.Yqd_Supervise.Where(it => it.IsDel == 0 && it.TaskID == TaskID && it.SuperviseType == 督导类型.督导);
            if (year > 0) r = r.Where(it => it.Instime.Year == year);
            data.AddRange(r.ToList().Select(it => new
            {
                it.TaskID,
                it.SuperviseID,
                CoordinateID = 0,
                CooperativeID = 0,
                ItemID = it.SuperviseID,
                ItemType = 事项类型.钉办督导,
                Principal = user.FirstOrDefault(m => m.EmployeeCode == it.EmployeeCode)?.Name,
                it.Status,
                it.Content,
                it.Instime
            }));
            var c = ctx.Yqd_Coordinate.Where(it => it.IsDel == 0 && it.TaskID == TaskID);
            if (year > 0) c = c.Where(it => it.Instime.Year == year);
            data.AddRange(c.ToList().Select(it => new
            {
                it.TaskID,
                SuperviseID = 0,
                it.CoordinateID,
                it.CooperativeID,
                ItemID = it.CoordinateID,
                ItemType = 事项类型.协同管理,
                it.Status,
                Principal = user.FirstOrDefault(m => m.EmployeeCode == it.Coordinator)?.Name,
                Content = it.Item,
                it.Instime
            }));
            if (Status > 0)
            {
                switch (Status)
                {
                    case 10:
                        var sIDs = ctx.Yqd_Scheme.Where(it => it.TaskID == TaskID && (it.ItemType == 事项类型.钉办督导 || it.ItemType == 事项类型.协同管理) && it.CheckStatus == 审核状态.待审).Select(it => it.ItemID).ToArray();
                        data = data.Where(it => sIDs.Contains((int)it.ItemID)).ToList();
                        break;
                    case 20:
                        sIDs = ctx.Yqd_PlanProgress.Where(it => it.TaskID == TaskID && (it.ItemType == 事项类型.钉办督导 || it.ItemType == 事项类型.协同管理) && it.CheckStatus == 审核状态.待审).Select(it => it.ItemID).ToArray();
                        data = data.Where(it => sIDs.Contains((int)it.ItemID)).ToList();
                        break;
                    case 30:
                        sIDs = ctx.Yqd_FinishReport.Where(it => it.TaskID == TaskID && (it.ItemType == 事项类型.钉办督导 || it.ItemType == 事项类型.协同管理) && it.CheckStatus == 审核状态.待审).Select(it => it.ItemID).ToArray();
                        data = data.Where(it => sIDs.Contains((int)it.ItemID)).ToList();
                        break;
                }
            }
            var platform = Form.GetInt("platform", 1);
            if (platform == 2)
            {
                var l = WxUser.LogonInfo;
                var sIDs = ctx.Yqd_Assign.Where(it => it.TaskID == TaskID && it.ItemType == 事项类型.精准督查 && (it.LeadUnit == l.UnitCode || ("," + it.CooperativeUnit + ",").Contains("," + l.UnitCode + ","))).Select(it => it.ItemID).ToArray();
                data = data.Where(it => sIDs.Contains((int)it.ItemID)).ToList();
            }
            var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            var TaskName = "";
            if (task != null) TaskName = task.TaskName;
            var cIDs = data.Select(it => it.CooperativeID).ToArray();
            var cooperative = ctx.Yqd_Cooperative.Where(it => it.IsDel == 0 && cIDs.Contains(it.CooperativeID)).Select(it => new { it.CooperativeID, it.CooperativeUnit }).ToList();
            return this.ToJson(new
            {
                success = true,
                totalcount = data.Count(),
                TaskName,
                data = data.Select(it => new
                {
                    it.SuperviseID,
                    it.CoordinateID,
                    Content = it.Content ?? "",
                    Instime = it.Instime.ToString("yyyy年M月d日"),
                    Status = it.Status.ToString(),
                    it.Principal,
                    cooperative.FirstOrDefault(d => d.CooperativeID == it.CooperativeID)?.CooperativeUnit,
                    Tag = it.ItemType.ToString()
                })
            });
        }

        [User]
        public ActionResult GetUnSuperviseList()
        {
            var ItemType = Form.GetInt("ItemType", (int)事项类型.钉办督导);
            var status = Form.GetInt("status");
            var code = Form.GetString("code");
            var year = Form.GetInt("Year");
            var taskID = Form.GetLong("TaskID");
            var key = Form.GetString("key");
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 5);
            var flag = Form.GetInt("flag", 1);


            var l = WxUser.LogonInfo;
            string sqlAssign = "";

            if (flag == 1)
            {
                status = (int)督导状态.滞后;
            }
            else if (flag == 2)
            {
                status = (int)督导状态.正常推进;
                sqlAssign = " and (DATEDIFF(day, CompleteLimit,getdate())>=-7 and DATEDIFF(day, CompleteLimit,getdate())<=0)"; //7天内
            }
            else if (flag == 3)
            {
                status = (int)督导状态.正常推进;
                sqlAssign = " and DateDiff(day,CompleteLimit,getdate())< -7"; //超出7天
            }
            else if (flag == 4)
            {
                status = (int)督导状态.已完成;
            }
            //var sql = $"1=1 and SuperviseID in (select ItemID from Yqd_Assign where (LeadUnit = '{l.UnitCode}' or CooperativeUnit like '%{l.UnitCode}%') {sqlAssign})";
            var sql = $"1=1 and SuperviseID in (select ItemID from Yqd_Assign where (LeadUnit = '{l.UnitCode}') {sqlAssign})";

            var zx = (事项类型)ItemType == 事项类型.专项交办 || (事项类型)ItemType == 事项类型.专项督查;
            if (status > 0)
            {
                switch ((督导状态)status)
                {
                    case 督导状态.当前待办:
                        sql += " and [SuperviseID] not in(select [ItemID] from Yqd_Assign where ItemType=" + ItemType + ")";
                        break;
                    case 督导状态.正常推进:
                        sql += " and [Status] in(" + (int)任务状态.预警 + "," + (int)任务状态.正常推进 + ")";
                        break;
                    case 督导状态.滞后:
                        sql += " and [Status]=" + (int)任务状态.滞后;
                        break;
                    case 督导状态.已完成:
                        sql += $" and ([Status]={(int)任务状态.已完成} or isFinish=1)";
                        break;
                    case 督导状态.钉办事项:
                        if (ItemType == (int)事项类型.钉办督导)
                            sql += " and [SuperviseType]=" + (int)督导类型.钉办;
                        break;
                }
            }
            if (code.Trim() != "")
            {
                sql += zx ? " and SuperviseID in(select ItemID from Yqd_Assign where ItemType =" + (int)事项类型.专项交办 + " and LeadUnit='" + code + "')" : " and TaskID in(select TaskID from Yqd_Task where LeaderUnitCode='" + code + "')";
            }
            if (year > 0)
            {
                sql += " and year(Instime)=" + year;
            }
            switch ((事项类型)ItemType)
            {
                case 事项类型.钉办督导:
                    if ((督导状态)status != 督导状态.钉办事项)
                    {
                        sql += " and [SuperviseType]!=" + (int)督导类型.钉办;
                    }
                    if (key.Trim() != "")
                    {
                        sql += " and TaskID in(select TaskID from Yqd_Task where IsDel=0 and lower(ltrim(rtrim([TaskName]))) like  '%" + key.ToLower().Trim() + "%' )";
                    }
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID, (case when SuperviseType= 10 then '钉办' else '督导' end) as Tag, Content, Status,EmployeeCode,0 as isFinish from Yqd_Supervise where " + sql + " and isdel=0 and [TaskID]>0 order by Instime desc";
                    break;
                case 事项类型.协同管理:
                    if (key.Trim() != "")
                    {
                        sql += " and TaskID in(select TaskID from Yqd_Task where IsDel=0 and lower(ltrim(rtrim([TaskName]))) like  '%" + key.ToLower().Trim() + "%' )";
                    }
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, CooperativeID, '协同' as Tag, Item as Content,EmployeeCode,0 as isFinish from Yqd_Cooperative where " + sql + " and isdel=0 order by Instime desc";
                    break;
                case 事项类型.精准督查:
                    if (key.Trim() != "")
                    {
                        sql += " and TaskID in(select TaskID from Yqd_Task where IsDel=0 and lower(ltrim(rtrim([TaskName]))) like  '%" + key.ToLower().Trim() + "%' )";
                    }
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID, '精准督查' as Tag, Problem as Content, Status,EmployeeCode,IsLb,0 as isFinish from Yqd_ExactSupervise where isDel=0 and " + sql + " order by Instime desc";
                    break;
                case 事项类型.专项交办:
                    if (taskID > 0) sql += " and [TaskID]=" + taskID;
                    if (key.Trim() != "")
                    {
                        sql += " and lower(ltrim(rtrim([TemplateData]))) like  '%" + key.ToLower().Trim() + "%' ";
                    }
                    zx = true;
                    if (flag == 4)
                    {
                    }
                    else
                    {
                        sql += " and isFinish=0 ";
                    }

                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID,TemplateID,TemplateData, '专项交办' as Tag, Status,EmployeeCode,IsFinish from Yqd_SpecialSupervise where isDel=0 and IsArchive=0 and " + sql + " and TaskType=" + (int)专项类型.专项交办 + " order by Instime desc";
                    break;
                case 事项类型.专项督查:
                    if (taskID > 0) sql += " and [TaskID]=" + taskID;
                    if (key.Trim() != "")
                    {
                        sql += " and lower(ltrim(rtrim([TemplateData]))) like  '%" + key.ToLower().Trim() + "%' ";
                    }
                    zx = true;

                    if (flag == 4)
                    {

                    }
                    else
                    {
                        sql += " and isFinish=0 ";
                    }
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID,TemplateID,TemplateData, '专项督查' as Tag, Status,EmployeeCode,IsFinish from Yqd_SpecialSupervise where isDel=0 and IsArchive=0 and " + sql + " and TaskType=" + (int)专项类型.专项督查 + " order by Instime desc";
                    break;
            }
            var data = ctx.Database.SqlQuery<SuperData>(sql);
            var taskList = new List<object>();
            var rs = new List<object>();
            if (zx)
            {
                //专项
                var tasks = ctx.Yqd_SpecialTask.Where(it => it.IsDel == 0 && it.Status == 栏目状态.正常).Select(it => new { it.TaskID, it.Name }).ToList();
                var re = UnSuperviceWhere(ItemType, status, year, 0, key, flag);
                var tids = re.Select(x => x.TaskID).ToList();

                foreach (var t in tasks.Where(x => tids.Any(y => y == x.TaskID)))
                {
                    taskList.Add(new
                    {
                        name = t.Name,
                        value = t.TaskID
                    });
                }
                var tps = ctx.Yqd_SpecialTemplate.Select(it => new { it.TaskID, it.TemplateID, it.Fields, it.IsDq }).ToList();
                var scheme = ctx.Yqd_Scheme.Where(it => it.ItemType == (事项类型)ItemType).Select(it => new { it.ItemID, it.JobTarget }).ToList();
                foreach (var d in data)
                {
                    string TaskName = "", Content = "";
                    JObject Targets = null;
                    var task = tasks.FirstOrDefault(it => it.TaskID == d.TaskID);
                    if (task != null) TaskName = task.Name;
                    Content = string.Join(" - ", scheme.Where(it => it.ItemID == d.SuperviseID).Select(it => it.JobTarget));
                    var f = tps.FirstOrDefault(it => it.TemplateID == d.TemplateID);
                    var fs = new JArray();
                    if (f != null && f.Fields.HasValue()) fs = JArray.Parse(f.Fields);
                    var TemplateData = d.TemplateData;
                    if (TemplateData.HasValue())
                    {
                        Targets = JObject.Parse(TemplateData);
                    }
                    string TargetsName = "";
                    string FieldName = "", FieldID = "";
                    var tp = tps.FirstOrDefault(it => it.TaskID == d.TaskID && it.IsDq);
                    if (tp != null && tp.Fields.HasValue())
                    {
                        var arr = JArray.Parse(tp.Fields);
                        var o = arr.FirstOrDefault(it => it["IsShow"] != null && it["IsShow"].ToString().ToLower() == "true");
                        if (o == null) o = arr[0];
                        FieldName = o["Name"]?.ToString() ?? "";
                        FieldID = o["FieldID"]?.ToString() ?? "";
                    }
                    if (TemplateData.HasValue() && FieldID != "")
                    {
                        TargetsName = JObject.Parse(TemplateData)[FieldID]?.ToString() ?? "";
                    }
                    var Fields = new List<object>();
                    if (Targets != null)
                    {
                        foreach (var o in fs)
                        {
                            var keys = o["FieldID"].ToString();
                            Fields.Add(new
                            {
                                text = o["Name"]?.ToString() ?? "",
                                value = Targets[keys]?.ToString() ?? ""
                            });
                        }
                    }
                    if (ItemType == (int)事项类型.专项督查)
                    {
                        ItemType = (int)事项类型.专项交办;
                    }
                    var a = ctx.Yqd_Assign.FirstOrDefault(it => it.ItemID == d.SuperviseID && it.ItemType == (事项类型)ItemType);
                    var UnitCode = a?.LeadUnit;
                    rs.Add(new
                    {
                        d.Num,
                        SuperviseID = 0,
                        CooperativeID = 0,
                        CoordinateID = 0,
                        ExactSuperviseID = 0,
                        TaskID = d.TaskID.ToString(),
                        SpecialsSuperviseID = d.SuperviseID,
                        TaskName,//任务名称
                        Fields,
                        FieldName,
                        Target = TargetsName,
                        LeadUnit = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == UnitCode || it.OrganizationCode == UnitCode)?.Name,//主办单位
                        d.Tag,
                        DealStatus = Enum.GetName(typeof(任务状态), d.Status),//办理状态
                        Content,//工作要求
                        Checker = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == d.EmployeeCode)?.Name,//交办人
                        CompleteLimit = a?.CompleteLimit.ToString("yyyy-MM-dd") ?? "",//完成时限
                        CheckInstime = a?.Instime.ToString("yyyy-MM-dd") ?? "", //交办时间
                        AssignLimit = a.Instime.ToString("yyyy-MM-dd") ?? "",
                        Status = Enum.GetName(typeof(任务状态), d.Status).Replace("推进", ""),
                        d.IsFinish
                    });
                }
            }
            else if (ItemType == (int)事项类型.精准督查)
            {
                var tIDs = data.Select(it => it.TaskID).ToArray();
                var tasks = ctx.Yqd_Task.Where(it => tIDs.Contains(it.TaskID)).Select(it => new { it.TaskID, it.TaskName, it.LeaderUnitName, it.TaskStatus }).ToList();
                //var person = ctx.Yqd_Person.Where(it => it.PersonType == 5).Select(it => new { it.TaskID, it.PersonName }).ToList();


                foreach (var d in data)
                {
                    var a = ctx.Yqd_Assign.FirstOrDefault(it => it.ItemID == d.SuperviseID && it.ItemType == (事项类型)ItemType);
                    var UnitCode = a?.LeadUnit;
                    dynamic t = null;
                    rs.Add(new
                    {
                        d.Num,
                        TaskID = d.TaskID.ToString(),
                        d.SuperviseID,
                        d.CoordinateID,
                        d.CooperativeID,
                        ExactSuperviseID = d.SuperviseID,
                        SpecialsSuperviseID = 0,
                        (t = tasks.FirstOrDefault(n => n.TaskID == d.TaskID))?.TaskName,//任务名称
                        LeadUnit = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == UnitCode || it.OrganizationCode == UnitCode)?.Name,//主办单位
                        //PersonName = person.FirstOrDefault(m => m.TaskID == d.TaskID)?.PersonName ?? "",
                        TaskStatus = Enum.GetName(typeof(任务状态), t.TaskStatus),
                        DealStatus = d.Tag != "钉办" ? Enum.GetName(typeof(任务状态), d.Status) : "",//办理状态
                        Checker = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == d.EmployeeCode)?.Name,//交办人
                        Tag = d.IsLb ? "督查回头看" : "精准督查",
                        Content = d.Content ?? "",//工作要求
                        CompleteLimit = a?.CompleteLimit.ToString("yyyy-MM-dd") ?? "",//完成时限
                        CheckInstime = a?.Instime.ToString("yyyy-MM-dd") ?? "", //交办时间
                        AssignLimit = a?.Instime.ToString("yyyy-MM-dd") ?? "",
                        Status = Enum.GetName(typeof(任务状态), d.Status).Replace("推进", ""),
                    });
                }
            }
            else if (ItemType == (int)事项类型.钉办督导)
            {
                var tIDs = data.Select(it => it.TaskID).ToArray();
                var tasks = ctx.Yqd_Task.Where(it => tIDs.Contains(it.TaskID)).Select(it => new { it.TaskID, it.TaskName, it.LeaderUnitName, it.TaskStatus }).ToList();
                //var person = ctx.Yqd_Person.Where(it => it.PersonType == 5).Select(it => new { it.TaskID, it.PersonName }).ToList();


                foreach (var d in data)
                {
                    var a = ctx.Yqd_Assign.FirstOrDefault(it => it.ItemID == d.SuperviseID && it.ItemType == (事项类型)ItemType);
                    var UnitCode = a?.LeadUnit;
                    dynamic t = null;
                    rs.Add(new
                    {
                        d.Num,
                        TaskID = d.TaskID.ToString(),
                        d.SuperviseID,
                        CooperativeID = 0,
                        CoordinateID = 0,
                        ExactSuperviseID = 0,
                        SpecialsSuperviseID = 0,
                        (t = tasks.FirstOrDefault(n => n.TaskID == d.TaskID))?.TaskName,//任务名称
                        LeadUnit = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == UnitCode || it.OrganizationCode == UnitCode)?.Name,//主办单位
                        //PersonName = person.FirstOrDefault(m => m.TaskID == d.TaskID)?.PersonName ?? "",
                        TaskStatus = Enum.GetName(typeof(任务状态), t.TaskStatus),
                        DealStatus = d.Tag != "钉办" ? Enum.GetName(typeof(任务状态), d.Status) : "",//办理状态
                        Checker = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == d.EmployeeCode)?.Name,//交办人
                        Tag = d.Tag,
                        Content = d.Content ?? "",//工作要求
                        CompleteLimit = a?.CompleteLimit.ToString("yyyy-MM-dd") ?? "",//完成时限
                        CheckInstime = a?.Instime.ToString("yyyy-MM-dd") ?? "", //交办时间
                        AssignLimit = a?.Instime.ToString("yyyy-MM-dd") ?? "",
                        Status = Enum.GetName(typeof(任务状态), d.Status).Replace("推进", ""),
                    });
                }
            }
            else if (ItemType == (int)事项类型.协同管理)
            {
                var tIDs = data.Select(it => it.TaskID).ToArray();
                var tasks = ctx.Yqd_Task.Where(it => tIDs.Contains(it.TaskID)).ToList();
                //var person = ctx.Yqd_Person.Where(it => it.PersonType == 5).Select(it => new { it.TaskID, it.PersonName }).ToList();


                foreach (var d in data)
                {
                    var a = ctx.Yqd_Assign.FirstOrDefault(it => it.ItemID == d.CooperativeID && it.ItemType == (事项类型)ItemType);
                    var UnitCode = a?.LeadUnit;
                    var t = tasks.FirstOrDefault(n => n.TaskID == d.TaskID);
                    rs.Add(new
                    {
                        d.Num,
                        TaskID = d.TaskID.ToString(),
                        SuperviseID = 0,
                        d.CooperativeID,
                        CoordinateID = 0,
                        SpecialsSuperviseID = 0,
                        ExactSuperviseID = 0,
                        TaskName = t == null ? "" : t.TaskName,//任务名称
                        LeaderUnitName = t == null ? "" : t.LeaderUnitName,//
                        LeadUnit = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == UnitCode || it.OrganizationCode == UnitCode)?.Name,//主办单位
                        //PersonName = person.FirstOrDefault(m => m.TaskID == d.TaskID)?.PersonName ?? "",
                        TaskStatus = Enum.GetName(typeof(任务状态), t.TaskStatus),
                        DealStatus = d.Tag != "钉办" ? Enum.GetName(typeof(任务状态), d.Status) : "",//办理状态
                        Checker = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == d.EmployeeCode)?.Name,//交办人
                        Tag = d.Tag,
                        Content = d.Content ?? "",//工作要求
                        CompleteLimit = a?.CompleteLimit.ToString("yyyy-MM-dd") ?? "",//完成时限
                        CheckInstime = a?.Instime.ToString("yyyy-MM-dd") ?? "", //交办时间
                        AssignLimit = a?.Instime.ToString("yyyy-MM-dd") ?? "",
                        Status = Enum.GetName(typeof(任务状态), d.Status).Replace("推进", ""),
                        CreateTime = t == null ? "" : t.CreateTime.ToString("yyyy-MM-dd"),
                    });
                }
            }
            return this.ToJson(new
            {
                success = true,
                totalcount = rs.Count(),
                data = rs.Skip((page - 1) * pagesize).Take(pagesize),
                tasks = taskList,
                sql
            });
        }


        [User]
        public ActionResult GetUnSuperviseList2()
        {
            var ItemType = Form.GetInt("ItemType", (int)事项类型.钉办督导);
            var year = Form.GetInt("year");
            var status = Form.GetInt("status");
            var key = Form.GetString("key");
            var taskID = Form.GetString("TaskID");

            var flag = Form.GetInt("flag", 1);
            if (flag > 4) flag = 4;
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 0);
            var l = WxUser.LogonInfo;
            var source = Form.GetString("source");
            //Logs.Information<UserHostService>($"GetUnSuperviseList用户登录信息 :{JsonConvert.SerializeObject(l)}，来源:{source}");
            var data = new List<dynamic>();
            var tIDs = new List<long>();

            ////专项交办督导

            var assign = ctx.Yqd_Assign.Where(it => it.LeadUnit == l.UnitCode).Select(it => new { it.TaskID, it.AssignID, it.ItemID, it.ItemType, it.ReportLimit, it.CompleteLimit, it.LeadUnit, it.Instime }).ToList();


            tIDs.AddRange(assign.Select(it => it.TaskID));
            //var plan = ctx.Yqd_JobPlan.Where(it => !string.IsNullOrWhiteSpace(it.TimeLine) && (it.UnitCode == l.UnitCode || ("," + it.CooperativeUnit + ",").Contains("," + l.UnitCode + ","))).ToList().Select(it => new { it.ItemID, it.ItemType, it.AssignID, it.UnitCode, TimeLine = DateTime.Parse(it.TimeLine.Split(',')[it.TimeLine.Split(',').Length - 1]) });
            var an = assign;
            var flow = ctx.Yqd_PlanFlow.Where(it => it.FlowMan == l.UnitCode).Select(it => new { it.TaskID, it.AssignID, it.ItemID, it.ItemType }).ToList();
            tIDs.AddRange(flow.Select(it => it.TaskID));


            var supervise = ctx.Yqd_Supervise.Where(it => it.IsDel == 0).Select(it => new { it.TaskID, it.SuperviseID, it.Content, it.Status, it.Instime }).ToList();
            var esupervise = ctx.Yqd_ExactSupervise.Where(x => !x.IsDel).Select(it => new { it.TaskID, it.SuperviseID, it.GUID, it.Problem, it.Status, it.Instime }).ToList();
            var ssupervise = ctx.Yqd_SpecialSupervise.Where(x => !x.IsDel && !x.IsArchive).ToList();
            var coordinate = ctx.Yqd_Coordinate.Where(it => it.IsDel == 0).Select(it => new { it.TaskID, it.CoordinateID, it.Item, it.Status, it.Instime }).ToList();
            var cooperative = ctx.Yqd_Cooperative.Where(it => it.IsDel == 0 && it.CooperativeUnit == l.UnitCode).Select(it => new { it.TaskID, it.CooperativeID, it.CooperativeResult, it.Item, it.RespondTime, it.Instime }).ToList();

            tIDs.AddRange(cooperative.Select(it => it.TaskID));
            var tasks = ctx.Yqd_Task.Where(it => it.IsShow).Select(it => new { it.TaskID, it.TaskName, it.LeaderUnitName, it.CreateTime, it.FAreaCode, it.TaskStatus }).ToList();
            var nt = DateTime.Now.Date;
            switch (flag)
            {
                case 0:
                case 1:
                    var slst = new List<int>();
                    slst.AddRange(assign.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).Distinct().ToArray());
                    supervise = supervise.Where(it => slst.Contains(it.SuperviseID) && it.Status == 任务状态.滞后).ToList();
                    slst.Clear();
                    slst.AddRange(assign.Where(it => it.ItemType == 事项类型.协同管理).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.协同管理).Select(it => it.ItemID).Distinct().ToArray());
                    coordinate = coordinate.Where(it => slst.Contains(it.CoordinateID) && it.Status == 任务状态.滞后).ToList();
                    slst.Clear();
                    slst.AddRange(assign.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).Distinct().ToArray());
                    esupervise = esupervise.Where(it => slst.Contains(it.SuperviseID) && it.Status == 任务状态.滞后).ToList();
                    slst.Clear();
                    slst.AddRange(assign.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
                    ssupervise = ssupervise.Where(it => slst.Contains(it.SuperviseID) && it.Status == 任务状态.滞后 && !it.IsFinish).ToList();
                    cooperative = cooperative.Where(it => nt > it.RespondTime && it.CooperativeResult == 协同结果.未反馈).ToList();
                    break;
                case 2:
                    slst = new List<int>();
                    slst.AddRange(an.Where(it => it.ItemType == 事项类型.钉办督导 && it.CompleteLimit.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
                    //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.钉办督导 && it.TimeLine.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).Distinct().ToArray());
                    supervise = supervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
                    slst.Clear();
                    slst.AddRange(an.Where(it => it.ItemType == 事项类型.协同管理 && it.CompleteLimit.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
                    //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.协同管理 && it.TimeLine.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.协同管理).Select(it => it.ItemID).Distinct().ToArray());
                    coordinate = coordinate.Where(it => slst.Contains(it.CoordinateID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
                    slst.Clear();
                    slst.AddRange(an.Where(it => it.ItemType == 事项类型.精准督查 && it.CompleteLimit.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
                    //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.精准督查 && it.TimeLine.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).Distinct().ToArray());
                    esupervise = esupervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
                    slst.Clear();
                    slst.AddRange(an.Where(it => it.ItemType == 事项类型.专项交办 && it.CompleteLimit.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
                    //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.专项交办 && it.TimeLine.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
                    ssupervise = ssupervise.Where(it => slst.Contains(it.SuperviseID) && !it.IsFinish && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
                    cooperative = cooperative.Where(it => it.RespondTime.Subtract(nt).Days <= 7 && it.CooperativeResult == 协同结果.未反馈).ToList();
                    break;
                case 3:
                    slst = new List<int>();
                    slst.AddRange(an.Where(it => it.ItemType == 事项类型.钉办督导 && it.CompleteLimit.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
                    //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.钉办督导 && it.TimeLine.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).Distinct().ToArray());
                    supervise = supervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
                    slst.Clear();
                    slst.AddRange(an.Where(it => it.ItemType == 事项类型.协同管理 && it.CompleteLimit.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
                    //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.协同管理 && it.TimeLine.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.协同管理).Select(it => it.ItemID).Distinct().ToArray());
                    coordinate = coordinate.Where(it => slst.Contains(it.CoordinateID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
                    slst.Clear();
                    slst.AddRange(an.Where(it => it.ItemType == 事项类型.精准督查 && it.CompleteLimit.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
                    //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.精准督查 && it.TimeLine.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).Distinct().ToArray());
                    esupervise = esupervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
                    slst.Clear();
                    slst.AddRange(an.Where(it => it.ItemType == 事项类型.专项交办 && it.CompleteLimit.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
                    //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.专项交办 && it.TimeLine.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
                    ssupervise = ssupervise.Where(it => slst.Contains(it.SuperviseID) && !it.IsFinish && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();

                    //Logs.Information<WxSuperviseController>("an:"+JsonConvert.SerializeObject(an.Where(it => it.ItemType == 事项类型.专项交办 && it.CompleteLimit.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray()));
                    //Logs.Information<WxSuperviseController>("plan:" + JsonConvert.SerializeObject(plan.Where(it => it.ItemType == 事项类型.专项交办 && it.TimeLine.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray()));
                    //Logs.Information<WxSuperviseController>("flow:" + JsonConvert.SerializeObject(flow.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray()));

                    cooperative = cooperative.Where(it => it.RespondTime.Subtract(nt).Days > 7 && it.CooperativeResult == 协同结果.未反馈).ToList();
                    break;
                case 4:
                    slst = new List<int>();
                    slst.AddRange(assign.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).Distinct().ToArray());
                    supervise = supervise.Where(it => slst.Contains(it.SuperviseID) && it.Status == 任务状态.已完成).ToList();
                    slst.Clear();
                    slst.AddRange(assign.Where(it => it.ItemType == 事项类型.协同管理).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.协同管理).Select(it => it.ItemID).Distinct().ToArray());
                    coordinate = coordinate.Where(it => slst.Contains(it.CoordinateID) && it.Status == 任务状态.已完成).ToList();
                    slst.Clear();
                    slst.AddRange(assign.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).Distinct().ToArray());
                    esupervise = esupervise.Where(it => slst.Contains(it.SuperviseID) && it.Status == 任务状态.已完成).ToList();
                    slst.Clear();
                    slst.AddRange(assign.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
                    slst.AddRange(flow.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
                    ssupervise = ssupervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.已完成 || it.IsFinish)).ToList();
                    cooperative = cooperative.Where(it => it.CooperativeResult != 协同结果.未反馈).ToList();
                    break;
            }
            dynamic t = null;
            if (supervise.Count > 0)
                data.AddRange(supervise.Select(it => new
                {
                    TaskID = it.TaskID.ToString(),
                    it.SuperviseID,
                    CooperativeID = 0,
                    CoordinateID = 0,
                    ExactSuperviseID = 0,
                    SpecialsSuperviseID = 0,
                    (t = tasks.FirstOrDefault(n => n.TaskID == it.TaskID))?.TaskName,
                    LeaderUnitName = t != null ? t.LeaderUnitName : "",
                    TaskStatus = Enum.GetName(typeof(任务状态), t.TaskStatus),
                    CreateTime = t != null ? t.CreateTime.ToString("yyyy-MM-dd") : "",
                    Content = it.Content ?? "",
                    Status = Enum.GetName(typeof(任务状态), t != null ? it.Status : 0).Replace("推进", ""),
                    AssignLimit = assign.FirstOrDefault(n => n.ItemID == it.SuperviseID && n.ItemType == 事项类型.钉办督导)?.Instime.ToString("yyyy-MM-dd"),
                    CompleteLimit = assign.FirstOrDefault(n => n.ItemID == it.SuperviseID && n.ItemType == 事项类型.钉办督导)?.CompleteLimit.ToString("yyyy-MM-dd"),
                    Tag = "督导",
                    it.Instime,
                    IsFinish = false
                }));
            t = null;
            if (coordinate.Count() > 0)
                data.AddRange(coordinate.Select(it => new
                {
                    TaskID = it.TaskID.ToString(),
                    SuperviseID = 0,
                    CooperativeID = 0,
                    SpecialsSuperviseID = 0,
                    ExactSuperviseID = 0,
                    it.CoordinateID,
                    (t = tasks.FirstOrDefault(n => n.TaskID == it.TaskID))?.TaskName,
                    t.LeaderUnitName,
                    TaskStatus = Enum.GetName(typeof(任务状态), t.TaskStatus),
                    CreateTime = t.CreateTime.ToString("yyyy-MM-dd"),
                    Content = it.Item ?? "",
                    Status = Enum.GetName(typeof(任务状态), it.Status).Replace("推进", ""),
                    AssignLimit = assign.FirstOrDefault(n => n.ItemID == it.CoordinateID && n.ItemType == 事项类型.协同管理)?.Instime.ToString("yyyy-MM-dd"),
                    CompleteLimit = assign.FirstOrDefault(n => n.ItemID == it.CoordinateID && n.ItemType == 事项类型.协同管理)?.CompleteLimit.ToString("yyyy-MM-dd"),
                    Tag = "协调",
                    it.Instime,
                    IsFinish = false
                }));
            t = null;
            if (cooperative.Count() > 0)
                data.AddRange(cooperative.Select(it => new
                {
                    TaskID = it.TaskID.ToString(),
                    SuperviseID = 0,
                    it.CooperativeID,
                    CoordinateID = 0,
                    SpecialsSuperviseID = 0,
                    ExactSuperviseID = 0,
                    (t = tasks.FirstOrDefault(n => n.TaskID == it.TaskID))?.TaskName,
                    t.LeaderUnitName,
                    TaskStatus = Enum.GetName(typeof(任务状态), t.TaskStatus),
                    Status = Enum.GetName(typeof(协同结果), it.CooperativeResult),
                    CreateTime = t.CreateTime.ToString("yyyy-MM-dd"),
                    Content = it.Item ?? "",
                    AssignLimit = it.RespondTime.ToString("yyyy-MM-dd"),
                    Tag = "协同",
                    it.Instime,
                    IsFinish = false
                }));
            if (esupervise.Count() > 0)
            {
                var ids = esupervise.Select(it => it.GUID).Distinct().ToArray();
                var pv = ctx.Yqd_ExactSupervise.Where(it => !it.IsDel && ids.Contains(it.GUID)).ToList();
                foreach (var id in ids)
                {
                    if (flag == 4 && pv.Any(it => it.GUID == id && it.Status != 任务状态.已完成))
                    {
                        continue;
                    }
                    var es = pv.Where(it => it.GUID == id);
                    var problem = "";
                    var i = 1;
                    dynamic o = null;
                    var Status = 任务状态.已完成;
                    var bl = false;
                    if (es.Any(it => it.Status == 任务状态.滞后))
                    {
                        Status = 任务状态.滞后;
                        bl = true;
                    }
                    else if (es.Any(it => it.Status == 任务状态.预警))
                    {
                        Status = 任务状态.预警;
                        bl = true;
                    }
                    else if (es.Any(it => it.Status == 任务状态.正常推进))
                    {
                        Status = 任务状态.正常推进;
                        bl = true;
                    }

                    foreach (var e in es)
                    {
                        problem += i + "、" + e.Problem + "  ";
                        if (o == null)
                        {
                            if (bl && e.Status == 任务状态.已完成) continue;
                            var AssignLimit = assign.FirstOrDefault(n => n.ItemID == e.SuperviseID && n.ItemType == 事项类型.精准督查)?.Instime.ToString("yyyy-MM-dd");
                            var CompleteLimit = assign.FirstOrDefault(n => n.ItemID == e.SuperviseID && n.ItemType == 事项类型.精准督查)?.CompleteLimit.ToString("yyyy-MM-dd");
                            o = new
                            {
                                e.TaskID,
                                e.SuperviseID,
                                e.Instime,
                                AssignLimit,
                                CompleteLimit
                            };
                        }
                        i++;
                    }
                    if (o == null) continue;
                    t = tasks.FirstOrDefault(n => n.TaskID == o.TaskID);
                    var TaskStatus = 0;
                    string TaskName = "", LeaderUnitName = "", CreateTime = "";
                    if (t != null)
                    {
                        TaskName = t.TaskName;
                        LeaderUnitName = t.LeaderUnitName;
                        TaskStatus = t.TaskStatus;
                        CreateTime = t.CreateTime.ToString("yyyy-MM-dd");
                    }
                    var exactSupervise = pv.Where(x => x.SuperviseID == o.SuperviseID).FirstOrDefault();
                    data.Add(new
                    {
                        TaskID = o.TaskID.ToString(),
                        SuperviseID = 0,
                        CooperativeID = 0,
                        CoordinateID = 0,
                        SpecialsSuperviseID = 0,
                        ExactSuperviseID = o.SuperviseID,
                        TaskName,
                        LeaderUnitName,
                        TaskStatus = Enum.GetName(typeof(任务状态), TaskStatus),
                        CreateTime,
                        Content = problem,
                        GUID = id,
                        Status = Status.ToString().Replace("推进", ""),
                        o.AssignLimit,
                        o.CompleteLimit,
                        Tag = exactSupervise.IsLb ? "督查回头看" : "精准督查",
                        o.Instime,
                        IsFinish = false
                    });
                }
            }
            if (ssupervise.Count() > 0)
            {
                var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
                var tmp = ctx.Yqd_SpecialTemplate.Select(it => new { it.TaskID, it.Fields, it.IsDq }).ToList();
                var UnitCodeList = assign.Select(it => it.LeadUnit).Distinct().ToList();
                var UnitList = ctx.Yqd_Unit.Where(it => UnitCodeList.Contains(it.UnitCode) || UnitCodeList.Contains(it.OrganizationCode)).ToList();
                foreach (var s in ssupervise)
                {
                    var Target = "";
                    string FieldName = "", FieldID = "";
                    var tp = tmp.FirstOrDefault(it => it.TaskID == s.TaskID && it.IsDq);
                    if (tp != null && tp.Fields.HasValue())
                    {
                        var arr = JArray.Parse(tp.Fields);
                        var o = arr.FirstOrDefault(it => it["IsShow"] != null && it["IsShow"].ToString().ToLower() == "true");
                        if (o == null) o = arr[0];
                        FieldName = o["Name"]?.ToString() ?? "";
                        FieldID = o["FieldID"]?.ToString() ?? "";
                    }
                    if (s.TemplateData.HasValue() && FieldID != "")
                    {
                        Target = JObject.Parse(s.TemplateData)[FieldID]?.ToString() ?? "";
                    }
                    var a = ctx.Yqd_Assign.FirstOrDefault(it => it.ItemID == s.SuperviseID && it.ItemType == 事项类型.专项交办);
                    var scheme = ctx.Yqd_Scheme.Where(it => it.ItemID == s.SuperviseID && it.ItemType == 事项类型.专项交办 && it.CheckStatus == 审核状态.同意);
                    var Content = string.Join(";", scheme.Select(it => it.JobTarget));

                    // plan.FirstOrDefault(it => it.ItemID == s.SuperviseID)?.UnitCode: 
                    var UnitCode = a?.LeadUnit;
                    data.Add(new
                    {
                        s.TaskID,
                        SuperviseID = 0,
                        CooperativeID = 0,
                        CoordinateID = 0,
                        ExactSuperviseID = 0,
                        SpecialsSuperviseID = s.SuperviseID,
                        FieldName,
                        Target,
                        LeadUnit = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == UnitCode || it.OrganizationCode == UnitCode)?.Name,//l.UnitName,
                        Checker = user.FirstOrDefault(it => it.EmployeeCode == s.EmployeeCode)?.Name,
                        CheckInstime = a?.Instime.ToString("yyyy-MM-dd") ?? "",
                        CompleteLimit = a?.CompleteLimit.ToString("yyyy-MM-dd") ?? "",
                        Content,
                        Status = Enum.GetName(typeof(任务状态), s.Status).Replace("推进", ""),
                        AssignLimit = a?.CompleteLimit.ToString("yyyy-MM-dd") ?? "",
                        Tag = Enum.GetName(typeof(专项类型), s.TaskType),
                        s.Instime,
                        s.IsFinish
                    });
                }
            }
            data = data.OrderByDescending(it => it.Instime).ToList();
            var totalcount = data.Count();
            if (pagesize > 0)
            {
                data = data.Skip((page - 1) * pagesize).Take(pagesize).ToList();
            }
            else
            {
                data = data.Take(2).ToList();
            }
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data,
            });
        }

        /// <summary>
        /// 督导意见
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_Supervise model)
        {
            var bl = model.SuperviseType == 督导类型.钉办;
            var fl = bl;
            if (!bl && string.IsNullOrWhiteSpace(model.Content))
            {
                ModelState.AddModelError("Content", "请填写督导意见");
            }
            if (!ModelState.IsValid)
            {
                return this.ToJson(new
                {
                    success = false,
                    stateMsg = from sk in ModelState.AsEnumerable()
                               where sk.Value.Errors.Count() > 0
                               select new { id = sk.Key, msg = sk.Value.Errors.FirstOrDefault().ErrorMessage }
                });
            }
            if (bl)
            {
                var m = ctx.Yqd_Supervise.FirstOrDefault(it => it.TaskID == model.TaskID && it.SuperviseType == Enm.督导类型.钉办);
                if (m == null) bl = false;
                else model = m;
            }
            model.Status = 任务状态.正常推进;
            model.IsRead = false;
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            if (!bl) ctx.Yqd_Supervise.Add(model);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                if (fl)
                {
                    var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == model.TaskID);
                    if (task != null)
                    {
                        //关闭通知
                        var msg = ddService.Notification(new List<string>(), "领导钉办", task.TaskID.ToString(), "任务名称：" + task.TaskName, WxUser.LogonInfo.Name + "市领导对该任务进行了钉办，请高度重视，抓紧推进。\n", superId: model.SuperviseID, pushStep: 推送流程.领导钉办, unitCode: WxUser.LogonInfo.UnitCode, employeeCode: model.EmployeeCode);
                        Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了领导钉办通知，返回值：" + msg);
                    }
                }
                else
                {
                    var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == model.TaskID);
                    if (task != null)
                    {
                        //关闭通知
                        var msg = ddService.Notification(new List<string>(), "领导督导", task.TaskID.ToString(), "任务名称：" + task.TaskName, WxUser.LogonInfo.Name + "市领导对该任务进行了督导，督导意见：" + model.Content + ",请及时交办。", superId: model.SuperviseID, pushStep: 推送流程.领导督导, unitCode: WxUser.LogonInfo.UnitCode, employeeCode: model.EmployeeCode);
                        Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了领导督导通知，返回值：" + msg);
                    }
                }
                TaskLogService.AddLog(model.TaskID, fl ? "要求钉办" : "提出了督导意见");
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
        [User]
        public ActionResult RevokeWork()
        {
            var bizMsgid = Form.GetString("bizMsgId");
            //var ar = cc.Split(',');
            //foreach(var item in ar)
            //{
            //    Thread.Sleep(1000);
            //}

            ddService.workRevoke(bizMsgid);

            return this.ToJson(new
            {
                success = true,
            });
        }


        [User]
        public ActionResult Delete()
        {
            var l = WxUser.LogonInfo;
            if (!l.Role.Contains(角色类型.管理员))
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "无权限删除"
                });
            }
            var SuperviseID = Form.GetInt("SuperviseID");
            var ret = ctx.Database.ExecuteSql("update Yqd_Supervise set IsDel=1 where SuperviseID={0};", SuperviseID);
            if (ret > 0)
            {
                var m = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                TaskLogService.AddLog(m.TaskID, "删除了督导意见(" + m.Content + ")");
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });

        }

        private List<SuperData> UnSuperviceWhere(int ItemType, int status, int year, long taskID, string key, int flag)
        {
            var l = WxUser.LogonInfo;
            string sqlAssign = "";

            if (flag == 1)
            {
                status = (int)督导状态.滞后;
            }
            else if (flag == 2)
            {
                status = (int)督导状态.正常推进;
                sqlAssign = " and (DATEDIFF(day, CompleteLimit,getdate())>=-7 and DATEDIFF(day, CompleteLimit,getdate())<=0)"; //7天内
            }
            else if (flag == 3)
            {
                status = (int)督导状态.正常推进;
                sqlAssign = " and DateDiff(day,CompleteLimit,getdate())< -7"; //超出7天
            }
            else if (flag == 4)
            {
                status = (int)督导状态.已完成;
            }
            //var sql = $"1=1 and SuperviseID in (select ItemID from Yqd_Assign where (LeadUnit = '{l.UnitCode}' or CooperativeUnit like '%{l.UnitCode}%') {sqlAssign})";

            var sql = $"1=1 and SuperviseID in (select ItemID from Yqd_Assign where (LeadUnit = '{l.UnitCode}') {sqlAssign})";

            var zx = (事项类型)ItemType == 事项类型.专项交办 || (事项类型)ItemType == 事项类型.专项督查;
            if (status > 0)
            {
                switch ((督导状态)status)
                {
                    case 督导状态.当前待办:
                        sql += " and [SuperviseID] not in(select [ItemID] from Yqd_Assign where ItemType=" + ItemType + ")";
                        break;
                    case 督导状态.正常推进:
                        sql += " and [Status] in(" + (int)任务状态.预警 + "," + (int)任务状态.正常推进 + ")";
                        break;
                    case 督导状态.滞后:
                        sql += " and [Status]=" + (int)任务状态.滞后;
                        break;
                    case 督导状态.已完成:
                        sql += " and [Status]=" + (int)任务状态.已完成;
                        break;
                    case 督导状态.钉办事项:
                        if (ItemType == (int)事项类型.钉办督导)
                            sql += " and [SuperviseType]=" + (int)督导类型.钉办;
                        break;
                }
            }
            if (year > 0)
            {
                sql += " and year(Instime)=" + year;
            }
            switch ((事项类型)ItemType)
            {
                case 事项类型.钉办督导:
                    if ((督导状态)status != 督导状态.钉办事项)
                    {
                        sql += " and [SuperviseType]!=" + (int)督导类型.钉办;
                    }
                    if (key.Trim() != "")
                    {
                        sql += " and TaskID in(select TaskID from Yqd_Task where IsDel=0 and lower(ltrim(rtrim([TaskName]))) like  '%" + key.ToLower().Trim() + "%' )";
                    }
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID, (case when SuperviseType= 10 then '钉办' else '督导' end) as Tag, Content, Status,EmployeeCode from Yqd_Supervise where " + sql + " and isdel=0 and [TaskID]>0 order by Instime desc";
                    break;
                case 事项类型.协同管理:
                    if (key.Trim() != "")
                    {
                        sql += " and TaskID in(select TaskID from Yqd_Task where IsDel=0 and lower(ltrim(rtrim([TaskName]))) like  '%" + key.ToLower().Trim() + "%' )";
                    }
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, CooperativeID, '协同' as Tag, Item as Content,EmployeeCode from Yqd_Cooperative where " + sql + " and isdel=0 order by Instime desc";
                    break;
                case 事项类型.精准督查:
                    if (key.Trim() != "")
                    {
                        sql += " and TaskID in(select TaskID from Yqd_Task where IsDel=0 and lower(ltrim(rtrim([TaskName]))) like  '%" + key.ToLower().Trim() + "%' )";
                    }
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID, '精准督查' as Tag, Problem as Content, Status,EmployeeCode,IsLb from Yqd_ExactSupervise where isDel=0 and " + sql + " order by Instime desc";
                    break;
                case 事项类型.专项交办:
                    if (taskID > 0) sql += " and [TaskID]=" + taskID;
                    if (key.Trim() != "")
                    {
                        sql += " and lower(ltrim(rtrim([TemplateData]))) like  '%" + key.ToLower().Trim() + "%' ";
                    }
                    zx = true;
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID,TemplateID,TemplateData, '专项交办' as Tag, Status,EmployeeCode from Yqd_SpecialSupervise where isDel=0 and isFinish=0 and IsArchive=0 and " + sql + " and TaskType=" + (int)专项类型.专项交办 + " order by Instime desc";
                    break;
                case 事项类型.专项督查:
                    if (taskID > 0) sql += " and [TaskID]=" + taskID;
                    if (key.Trim() != "")
                    {
                        sql += " and lower(ltrim(rtrim([TemplateData]))) like  '%" + key.ToLower().Trim() + "%' ";
                    }
                    zx = true;
                    sql = "select ROW_NUMBER() over(order by [Instime] desc) as Num, TaskID, SuperviseID,TemplateID,TemplateData, '专项督查' as Tag, Status,EmployeeCode from Yqd_SpecialSupervise where isDel=0 and isFinish=0 and IsArchive=0 and " + sql + " and TaskType=" + (int)专项类型.专项督查 + " order by Instime desc";
                    break;
            }
            var data = ctx.Database.SqlQuery<SuperData>(sql);
            return data;
        }
        [User]
        public ActionResult GetUnSuperviseCount()
        {
            var ItemType = Form.GetInt("ItemType", (int)事项类型.钉办督导);
            var status = Form.GetInt("status");
            var year = Form.GetInt("Year");
            var taskID = Form.GetLong("TaskID");
            var key = Form.GetString("key");
            var flag = Form.GetInt("flag", 1);

            return this.ToJson(new
            {
                success = true,
                zhCount = UnSuperviceWhere(ItemType, status, year, taskID, key, flag).Count,
                qtCount = UnSuperviceWhere(ItemType, status, year, taskID, key, 2).Count,
                qwCount = UnSuperviceWhere(ItemType, status, year, taskID, key, 3).Count
            });
        }

        [User]
        public ActionResult GetUnSuperviseCount2()
        {
            var l = WxUser.LogonInfo;

            var source = Form.GetString("source");
            //Logs.Information<UserHostService>($"GetUnSuperviseCount用户登录信息 :{JsonConvert.SerializeObject(l)}，来源:{source}");

            var taskIDs = ctx.Yqd_Task.Where(it => it.IsShow).Select(it => it.TaskID).ToArray();
            var assign = ctx.Yqd_Assign.Where(it => it.LeadUnit == l.UnitCode).Select(it => new { it.TaskID, it.AssignID, it.ItemID, it.ItemType, it.CompleteLimit, it.LeadUnit }).ToList();
            //var plan = ctx.Yqd_JobPlan.Where(it => !string.IsNullOrWhiteSpace(it.TimeLine) && (it.UnitCode == l.UnitCode)).ToList().Select(it => new { it.TaskID, it.ItemID, it.ItemType, it.AssignID, TimeLine = DateTime.Parse(it.TimeLine.Split(',')[it.TimeLine.Split(',').Length - 1]) });
            //var an = assign.Where(it => !plan.Any(m => m.AssignID == it.AssignID));
            var an = assign;
            var flow = ctx.Yqd_PlanFlow.Where(it => it.FlowMan == l.UnitCode).Select(it => new { it.TaskID, it.AssignID, it.ItemID, it.ItemType }).ToList();
            var supervise = ctx.Yqd_Supervise.Where(it => it.IsDel == 0).Select(it => new { it.TaskID, it.SuperviseID, it.Content, it.Status, it.Instime }).ToList();
            var esupervise = ctx.Yqd_ExactSupervise.Where(it => !it.IsDel).Select(it => new { it.TaskID, it.SuperviseID, it.GUID, it.Problem, it.Status, it.Instime }).ToList();
            var ssupervise = ctx.Yqd_SpecialSupervise.Where(x => !x.IsDel && !x.IsFinish && !x.IsArchive).ToList();
            var coordinate = ctx.Yqd_Coordinate.Where(it => it.IsDel == 0).Select(it => new { it.TaskID, it.CoordinateID, it.Item, it.Status, it.Instime }).ToList();
            var cooperative = ctx.Yqd_Cooperative.Where(it => it.IsDel == 0 && it.CooperativeUnit == l.UnitCode).Select(it => new { it.TaskID, it.CooperativeID, it.CooperativeResult, it.Item, it.RespondTime, it.Instime }).ToList();
            var nt = DateTime.Now.Date;
            int zhCount = 0, qtCount = 0, qwCount = 0;
            //获取滞后任务总数
            var slst = new List<int>();
            slst.AddRange(assign.Where(it => it.ItemType == 事项类型.钉办督导 && taskIDs.Contains(it.TaskID)).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.钉办督导 && taskIDs.Contains(it.TaskID)).Select(it => it.ItemID).Distinct().ToArray());
            var rs = supervise.Where(it => slst.Contains(it.SuperviseID) && it.Status == 任务状态.滞后).ToList();
            slst.Clear();
            slst.AddRange(assign.Where(it => it.ItemType == 事项类型.协同管理 && taskIDs.Contains(it.TaskID)).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.协同管理 && taskIDs.Contains(it.TaskID)).Select(it => it.ItemID).Distinct().ToArray());
            var cs = coordinate.Where(it => slst.Contains(it.CoordinateID) && it.Status == 任务状态.滞后).ToList();
            slst.Clear();
            slst.AddRange(assign.Where(it => it.ItemType == 事项类型.精准督查 && taskIDs.Contains(it.TaskID)).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.精准督查 && taskIDs.Contains(it.TaskID)).Select(it => it.ItemID).Distinct().ToArray());
            var es = esupervise.Where(it => slst.Contains(it.SuperviseID) && it.Status == 任务状态.滞后).ToList();
            slst.Clear();
            slst.AddRange(assign.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
            var ss = ssupervise.Where(it => slst.Contains(it.SuperviseID) && it.Status == 任务状态.滞后).ToList();
            var cos = cooperative.Where(it => nt > it.RespondTime && it.CooperativeResult == 协同结果.未反馈).ToList();
            zhCount += rs.Count + cs.Count() + cos.Count() + ss.Count();
            zhCount += es.Select(it => it.GUID).Distinct().Count();
            slst.Clear();
            //获取7天内任务总数
            slst.AddRange(an.Where(it => it.ItemType == 事项类型.钉办督导 && taskIDs.Contains(it.TaskID) && it.CompleteLimit.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
            //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.钉办督导 && taskIDs.Contains(it.TaskID) && it.TimeLine.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).Distinct().ToArray());
            rs = supervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
            slst.Clear();
            slst.AddRange(an.Where(it => it.ItemType == 事项类型.协同管理 && taskIDs.Contains(it.TaskID) && it.CompleteLimit.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
            //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.协同管理 && taskIDs.Contains(it.TaskID) && it.TimeLine.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.协同管理).Select(it => it.ItemID).Distinct().ToArray());
            cs = coordinate.Where(it => slst.Contains(it.CoordinateID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
            slst.Clear();
            slst.AddRange(an.Where(it => it.ItemType == 事项类型.精准督查 && taskIDs.Contains(it.TaskID) && it.CompleteLimit.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
            //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.精准督查 && taskIDs.Contains(it.TaskID) && it.TimeLine.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).Distinct().ToArray());
            es = esupervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
            slst.Clear();
            slst.AddRange(an.Where(it => it.ItemType == 事项类型.专项交办 && it.CompleteLimit.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
            //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.专项交办 && it.TimeLine.Subtract(nt).Days <= 7).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
            ss = ssupervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
            cos = cooperative.Where(it => it.RespondTime.Subtract(nt).Days <= 7 && it.CooperativeResult == 协同结果.未反馈).ToList();
            qtCount += rs.Count + cs.Count() + cos.Count() + ss.Count();
            qtCount += es.Select(it => it.GUID).Distinct().Count();
            slst.Clear();
            //获取7天以上任务总数
            slst.AddRange(an.Where(it => it.ItemType == 事项类型.钉办督导 && taskIDs.Contains(it.TaskID) && it.CompleteLimit.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
            //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.钉办督导 && taskIDs.Contains(it.TaskID) && it.TimeLine.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).Distinct().ToArray());
            rs = supervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
            slst.Clear();
            slst.AddRange(an.Where(it => it.ItemType == 事项类型.协同管理 && taskIDs.Contains(it.TaskID) && it.CompleteLimit.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
            //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.协同管理 && taskIDs.Contains(it.TaskID) && it.TimeLine.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.协同管理).Select(it => it.ItemID).Distinct().ToArray());
            cs = coordinate.Where(it => slst.Contains(it.CoordinateID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
            slst.Clear();
            slst.AddRange(an.Where(it => it.ItemType == 事项类型.精准督查 && taskIDs.Contains(it.TaskID) && it.CompleteLimit.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
            //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.精准督查 && taskIDs.Contains(it.TaskID) && it.TimeLine.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).Distinct().ToArray());
            es = esupervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
            slst.Clear();
            slst.AddRange(an.Where(it => it.ItemType == 事项类型.专项交办 && it.CompleteLimit > nt.AddDays(7)).Select(it => it.ItemID).Distinct().ToArray());
            //slst.AddRange(plan.Where(it => it.ItemType == 事项类型.专项交办 && it.TimeLine.Subtract(nt).Days > 7).Select(it => it.ItemID).Distinct().ToArray());
            slst.AddRange(flow.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).Distinct().ToArray());
            ss = ssupervise.Where(it => slst.Contains(it.SuperviseID) && (it.Status == 任务状态.正常推进 || it.Status == 任务状态.预警)).ToList();
            cos = cooperative.Where(it => it.RespondTime.Subtract(nt).Days > 7 && it.CooperativeResult == 协同结果.未反馈).ToList();
            qwCount += rs.Count + cs.Count() + cos.Count() + ss.Count();
            qwCount += es.Select(it => it.GUID).Distinct().Count();
            return this.ToJson(new
            {
                success = true,
                zhCount,
                qtCount,
                qwCount
            });
        }

        private (string UnitCode, string UnitName) GetUnit(string OrganizationCode)
        {
            var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrganizationCode);
            if (org == null)
            {
                return ("", "");
            }
            if (org.TypeCode == "GOV_UNIT")
            {
                var unit = ctx.Yqd_Unit.Where(x => x.OrganizationCode == org.OrganizationCode).FirstOrDefault();
                if (unit != null)
                {
                    UnitCode = unit.UnitCode;
                    UnitName = unit.Name;
                }
                else
                {
                    UnitCode = org.OrganizationCode;
                    UnitName = org.Name;
                }
            }
            if (org.TypeCode == "GOV_HOLLOW_STRIP_NODE")
            {
                return (UnitCode, UnitName);
            }
            return GetUnit(org.ParentCode);
        }
    }
}
